﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Model;

namespace iLangl.Customer.DAL.XMLStorage
{
	public class ProductDAL : BaseStorageDAL, IProductDAL
	{
		#region IProductDAL Members

		public void AddProduct(Model.Product product, System.Data.IDbTransaction trans)
		{
			dtoXmlStorage.ProductRow productRow = Storage.Product.FindById(product.Id);

			bool isNew = (productRow == null);

			if (isNew)
			{
				productRow = Storage.Product.NewProductRow();
			}

			productRow.Description = product.Description;
			productRow.Id = product.Id;
			productRow.Name = product.Name;

			if (isNew)
			{
				Storage.Product.AddProductRow(productRow);
			}

			if (trans == null)
			{
				AcceptChanges();
			}
		}

	
		public Product ReadProductById(string id)
		{
			dtoXmlStorage.ProductRow productRow = Storage.Product.FindById(id);

			if (productRow == null)
				return null;

			Product result = new Product();
			result.Id = productRow.Id;

			if (!productRow.IsNameNull())
				result.Name = productRow.Name;

			if(!productRow.IsDescriptionNull())
				result.Description = productRow.Description;


			return result;
		}

		public Product ReadProductByName(string name)
		{
			foreach (dtoXmlStorage.ProductRow pr in Storage.Product)
			{
				if (string.Compare(name, pr.Name, true) == 0)
				{
					return ReadProductById(pr.Id);
				}
			}

			return null;

		}

		#endregion
	}
}
